# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from core.signals import collect_hotwords
from django.dispatch import receiver
from django.db import models

# Create your models here.

class HotWords(models.Model):
    word = models.CharField(u"关键词", max_length=64, db_index=True)
    model = models.CharField(u"数据模型", max_length=64, db_index=True, blank=True, null=True)
    rate = models.BigIntegerField(u"热度", default=1, db_index=True)

    def __str__(self):
        return u"%s" % self.word

    class Meta:
        verbose_name = verbose_name_plural = '热搜词'


@receiver(collect_hotwords)
def collect_words_callback(sender, words, **kwargs):
    '''
    收集搜索关键词
    '''
    model_name = None
    if isinstance(sender, models.Model.__class__):
        model_name = "%s.%s" % (sender._meta.app_label, sender.__name__)
    if isinstance(words, (tuple, list)):
        w_list = [w.strip() for w in words if len(w.strip()) > 1]
    else:
        w_list = [w for w in words.strip().split(' ') if len(w) > 1]

    for w in w_list:
        obj, created = HotWords.objects.get_or_create(word=w.strip(), model=model_name.lower(), defaults={'rate': 1})
        if not created:
            obj.rate = obj.rate+1
            obj.save()
